<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="产线编码" prop="lineCode">
        <el-input v-model="searchForm.lineCode" placeholder="请输入产线编码" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="产线名称" prop="lineName">
        <el-input v-model="searchForm.lineName" placeholder="请输入产线名称" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="所属工厂" prop="factoryId">
        <el-select
          v-model="searchForm.factoryId"
          placeholder="请选择工厂"
          clearable
          style="width: 180px"
          @change="handleSearchFactoryChange"
        >
          <el-option v-for="factory in searchFactoryList" :key="factory.id" :label="factory.factoryName" :value="factory.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属车间" prop="workshopId">
        <el-select
          v-model="searchForm.workshopId"
          placeholder="请选择车间"
          clearable
          style="width: 180px"
          :disabled="!searchForm.factoryId"
        >
          <el-option
            v-for="workshop in searchWorkshopList"
            :key="workshop.id"
            :label="workshop.workshopName"
            :value="workshop.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产线状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
          <el-option label="启用" value="enable" />
          <el-option label="停用" value="disable" />
        </el-select>
      </el-form-item>
      <el-form-item label="产线类型" prop="lineType">
        <el-select v-model="searchForm.lineType" placeholder="请选择类型" clearable style="width: 120px">
          <el-option label="装配线" value="ASSEMBLY" />
          <el-option label="测试线" value="TESTING" />
          <el-option label="包装线" value="PACKAGING" />
          <el-option label="检验线" value="INSPECTION" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增产线</el-button>
      <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="lineCode" label="产线编码" width="120" />
      <el-table-column prop="lineName" label="产线名称" width="120" />
      <el-table-column prop="factoryName" label="所属工厂" width="120" />
      <el-table-column prop="workshopName" label="所属车间" width="120" />
      <el-table-column prop="lineType" label="产线类型" width="100">
        <template #default="scope">
          {{ formatLineType(scope.row.lineType) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'enable' ? 'success' : 'danger'">
            {{ scope.row.status === "enable" ? "启用" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置" width="200" show-overflow-tooltip />
      <el-table-column prop="maxDeviceCapacity" label="最大设备数" min-width="100" />
      <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="deleteProductionLine(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <ProductionLineDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import ProductionLineDrawer from "./form.vue";
import {
  getProductionLineList,
  createProductionLine,
  updateProductionLine,
  deleteProductionLine as deleteProductionLineApi,
  batchDeleteProductionLine,
  getEnabledFactoryList,
  getEnabledWorkshopsByFactoryId,
  type ProductionLine
} from "@/api/modules/productionLine";

const loading = ref(false);
const tableData = ref<ProductionLine.ProductionLineListItem[]>([]);
const selectedRows = ref<ProductionLine.ProductionLineListItem[]>([]);

// 搜索用的工厂和车间数据
const searchFactoryList = ref<{ id: string; factoryName: string }[]>([]);
const searchWorkshopList = ref<{ id: string; workshopName: string }[]>([]);

// 搜索表单
const searchForm = reactive({
  lineCode: "",
  lineName: "",
  factoryId: undefined as string | undefined,
  workshopId: undefined as string | undefined,
  status: "",
  lineType: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize
    };
    const res = await getProductionLineList(params);
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    ElMessage.error("获取产线列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取搜索用的工厂列表
const loadSearchFactoryList = async () => {
  try {
    const res = await getEnabledFactoryList();
    searchFactoryList.value = res.data || [];
  } catch (error) {
    console.error("获取工厂列表失败:", error);
  }
};

// 获取搜索用的车间列表
const loadSearchWorkshopList = async (factoryId: string) => {
  try {
    const res = await getEnabledWorkshopsByFactoryId(factoryId);
    searchWorkshopList.value = res.data || [];
  } catch (error) {
    console.error("获取车间列表失败:", error);
    searchWorkshopList.value = [];
  }
};

// 搜索工厂选择变化处理
const handleSearchFactoryChange = (factoryId: string) => {
  searchForm.workshopId = undefined;
  searchWorkshopList.value = [];
  if (factoryId) {
    loadSearchWorkshopList(factoryId);
  }
};

// 格式化产线类型
const formatLineType = (type: string) => {
  const types: Record<string, string> = {
    ASSEMBLY: "装配线",
    TESTING: "测试线",
    PACKAGING: "包装线",
    INSPECTION: "检验线"
  };
  return types[type] || type;
};

// 表格选择项变化
const handleSelectionChange = (rows: ProductionLine.ProductionLineListItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条产线吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteProductionLine(ids);
      ElMessage.success("批量删除成功");
      getTableData();
    } catch (error) {
      ElMessage.error("批量删除失败");
    }
  });
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    lineCode: "",
    lineName: "",
    factoryId: undefined,
    workshopId: undefined,
    status: "",
    lineType: ""
  });
  searchWorkshopList.value = [];
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 删除产线
const deleteProductionLine = async (row: ProductionLine.ProductionLineListItem) => {
  try {
    await deleteProductionLineApi(row.id);
    ElMessage.success(`删除产线【${row.lineName}】成功`);
    getTableData();
  } catch (error) {
    ElMessage.error("删除产线失败");
  }
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof ProductionLineDrawer>>();
const openDrawer = (title: string, row: Partial<ProductionLine.ProductionLineListItem> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addProductionLine : title === "编辑" ? editProductionLine : undefined,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 新增产线
const addProductionLine = async (params: ProductionLine.CreateProductionLineRequestDto) => {
  return await createProductionLine(params);
};

// 编辑产线
const editProductionLine = async (params: ProductionLine.ProductionLineListItem) => {
  return await updateProductionLine(params.id, params);
};

// 初始化数据
onMounted(() => {
  getTableData();
  loadSearchFactoryList();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}
.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 16px;
  margin: 0 5px;
}

:deep(.operation-btn .el-icon) {
  font-size: 18px;
  margin-right: 4px;
}
</style>
